package org.jetlinks.pro.assets.impl.terms;

import org.apache.commons.collections4.CollectionUtils;
import org.hswebframework.ezorm.core.param.Term;
import org.hswebframework.ezorm.rdb.metadata.RDBColumnMetadata;
import org.hswebframework.ezorm.rdb.operator.builder.fragments.PrepareSqlFragments;
import org.hswebframework.ezorm.rdb.operator.builder.fragments.SqlFragments;
import org.hswebframework.ezorm.rdb.operator.builder.fragments.term.AbstractTermFragmentBuilder;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Collection;

@Component
public class DimensionAssetsTermBuilder extends AbstractTermFragmentBuilder {

    public static final String termType = "dim-assets";

    public DimensionAssetsTermBuilder() {
        super(termType, "资产查询");
    }

    // exists(select 1 from s_dimension_assets_bind _bind
    // where _bind.asset_type =?
    //      and t.id = _bind.asset_id
    //      and _bind.target_key in(?,?)
    // )
    @Override
    public SqlFragments createFragments(String columnFullName, RDBColumnMetadata column, Term term) {

        DimensionAssetsTerm assetsTerm = DimensionAssetsTerm.of(term);
        boolean not = Boolean.TRUE.equals(assetsTerm.getNot());

        Collection<Object> targetKeys = assetsTerm.toTargetKeys();

        String[] args = new String[targetKeys.size()];
        Arrays.fill(args, "?");

        PrepareSqlFragments sqlFragments = PrepareSqlFragments.of();
        sqlFragments
            .addSql(not ? "not" : "")
            .addSql("exists(select 1 from s_dimension_assets_bind _bind")
            .addSql("where _bind.asset_type = ?").addParameter(String.valueOf(assetsTerm.getAssetType()))
            .addSql("and", columnFullName, "= _bind.asset_id")
            .addSql("and _bind.target_key in(", String.join(",", args), ")")
            .addParameter(targetKeys);

        if (CollectionUtils.isNotEmpty(assetsTerm.getRelations())) {
            String[] relations = new String[assetsTerm.getRelations().size()];
            Arrays.fill(relations, "?");

            sqlFragments.addSql("and _bind.relation in(", String.join(",", relations), ")")
                        .addParameter(assetsTerm.getRelations());
        }
        sqlFragments.addSql(")");
        return sqlFragments;
    }
}
